package com.huaxin.hxcloud.fragment;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;

import java.util.Calendar;

/**
 * Created by Administrator on 2017/8/9.
 * 一个用于选择日期的对话框，用diologFragment实现
 */

@SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{


    private Context mContext;
    private OnDatePickedListenner mOnDatePickedListenner;
    private String tag;//一个标记，用于确定是哪个按钮启动了该fragment

    public static  DatePickerFragment newInstance(Context context,String tag){

        return new DatePickerFragment(context,tag);
    }

    private DatePickerFragment(Context context, String tag){
        this.mContext=context;
        if (context instanceof OnDatePickedListenner) {
            this.mOnDatePickedListenner = (OnDatePickedListenner) context;
        } else {
            throw new RuntimeException("you must implement OnDatePickedListenner in activity");
        }

        this.tag=tag;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext=context;
        Bundle arguments = getArguments();
        this.tag = arguments.getString("tag");
        if (context instanceof OnDatePickedListenner) {
            this.mOnDatePickedListenner = (OnDatePickedListenner) context;
        } else {
            throw new RuntimeException("you must implement OnDatePickedListenner in activity");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        // Create a new instance of DatePickerDialog and return it
        //Log.i("lwjing","context="+mContext+"year month day  "+year+month+day);
        return new DatePickerDialog(mContext, this, year, month, day);
    }

    /**
     * 选中日期时回调,将此结果回调到
     * 实现了OnDatePickedListenner的activity
     * @param view
     * @param year
     * @param month
     * @param dayOfMonth
     */
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        if (mOnDatePickedListenner != null) {
            mOnDatePickedListenner.onDatePicked(tag,year,month,dayOfMonth);
        }
    }
    public interface OnDatePickedListenner{
        void onDatePicked(String tag,int year,int month,int dayOfMonth);
    }
}
